#!/bin/bash

cd "/home/enoteserver/htdocs/fileadmin/enoteserver/temp/"

if [ -e generate.lck ]; then
	PID=`head -n 1 generate.lck`
	echo "PID AF GENERATE: ${PID}"
	if [ -n "$PID" ]; then
		RUNNING=`ps -p ${PID} -Ocommand | grep ${0} 2>/dev/null`
		echo ${RUNNING}
	fi
	if [ -z "${RUNNING}" ]; then
		echo "NOT RUNNING"
		echo $$ > generate.lck
	else
		echo "Placing ticket"
		echo $$ > $1".ticket"
		exit 0;
	fi
else 
	echo $$ > generate.lck
fi
echo $$ > $1".ticket"

KEY=${1}

generate() {
	echo "Generating ${KEY}.tex .."
echo "pdflatex "
/usr/bin/pdflatex -halt-on-error --shell-escape "${KEY}.tex" >"${KEY}.scriptlog" 2>&1
echo "makeindex.. "
makeindex "${KEY}.idx" >"${KEY}.scriptlog" 2>&1

echo "pdflatex"
/usr/bin/pdflatex -halt-on-error --shell-escape "${KEY}.tex" >"${KEY}.scriptlog" 2>&1
if [ $? -ne 0 ]; then
	rm "${KEY}."{idx,idg,out,aux,pdf,ilg,ind}
	echo ".. FAILED!\n"
else
	echo ".. SUCCESS!\n"
	rm "${KEY}."{idx,idg,out,aux,log,ilg,ind,scriptlog}
fi

rm "${KEY}.ticket"
}

generate


while [ 1 ]; do
	OLDEST_TICKET=`ls -1Ut | grep ".ticket" | tail -1`
	echo ${OLDEST_TICKET}
	if [ -z "${OLDEST_TICKET}" ];then
		rm generate.lck
		exit 0
	fi
	KEY=${OLDEST_TICKET%%.*}
	generate
done